/*
 * font2hex.c
 *
 *  Created on: 06.12.2009
 *      Author: pasha
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include "../aliens/quicklz/quicklz.c"

static void help()
{
	printf("use font2hex fontfile \n");
	exit(-1);
}



static void replaceDot(char** str)
{
	char * rabbit;
	size_t length=strlen(*str);
	for(rabbit=*str; rabbit - *str < length; rabbit++)
	{
		if (*rabbit == '.' || *rabbit == '/'
			|| *rabbit == '\\' || *rabbit == ' '
			|| 	*rabbit == '-'
		)
			*rabbit = '_';
	}
}

static void hex2font(char* file)
{
	int filesize,resultSize;
	FILE *fd;
	unsigned char * src, *dst, *scratch, *rabbit;
	fd = fopen(file,"r");
	if(!fd)
		help();
	fseek(fd,0L,SEEK_END);
	filesize = ftell(fd);

	printf("/* quicklz binary file */\n");
	printf("/* %i bytes*/\n",filesize);

	src = (unsigned char*) malloc(filesize);

	fseek(fd,0L,SEEK_SET);
	fread(src,1, filesize,fd);
	fclose(fd);


	dst = malloc(filesize);
	scratch = malloc(QLZ_SCRATCH_COMPRESS);

	resultSize = qlz_compress(src,(char*)dst, filesize, (char*)scratch);
	free(src);


	replaceDot(&file);
	printf("static unsigned char %s[]={\n",file);

	rabbit = dst;
	while(rabbit -dst < resultSize)
	{
		if(rabbit != dst)
		{
			printf(",");
		}
		printf("0x%.2x",*rabbit);
		rabbit++;

		if (!((rabbit -dst) %0x1F))
			printf("\n");
	}
	printf("\n};\n");

	free(scratch);
	free(dst);
}




int main(int argc, char **argv)
{
	if(argc != 2)
		help();

	hex2font(argv[1]);
	return 0;
}
